package org.ecinc.mvc.util;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class XMLParse {

	@SuppressWarnings("unchecked")
	public static Map<String, XMLBean> parseXml(String xmlPath) throws Exception {
		Map<String, XMLBean> rmap = new HashMap<String, XMLBean>();
		
		SAXBuilder builder = new SAXBuilder();
		Document document = builder.build(new File(xmlPath));
		Element root = document.getRootElement();
		
		Element actionRoot = root.getChild("action-mappings");
		List<Element> actionList = actionRoot.getChildren();
		for(Element e : actionList){
			XMLBean bean = new XMLBean();
			String name = e.getAttributeValue("name");
			bean.setBeanName(name);
			Element formRoot = root.getChild("form-beans");
			List<Element> formList = formRoot.getChildren();
			for(Element ef : formList){
				if(name.equals(ef.getAttributeValue("name"))){
					String formClass = ef.getAttributeValue("type");
					bean.setFormClass(formClass);
					break;
				}
			}
			String path = e.getAttributeValue("path");
			bean.setPath(path);
			String type = e.getAttributeValue("type");
			bean.setActionClass(type);
			List<Element> forwardList = e.getChildren();
			Map<String, String> forwardMap = new HashMap<String, String>();
			for(Element fe : forwardList){
				forwardMap.put(fe.getAttributeValue("name"), fe.getAttributeValue("path"));
			}
			bean.setActionForward(forwardMap);
			rmap.put(path, bean);
		}
		
		return rmap;
	}
	
	public static void main(String[] args) throws Exception {
		Map<String, XMLBean> map = XMLParse.parseXml("D:\\workspace\\mvc\\WebRoot\\WEB-INF\\struts-config.xml");
		Set<String> set = map.keySet();
		for(Iterator<String> it = set.iterator();it.hasNext();){
			String key = it.next();
			System.out.println("key=" + key);
			XMLBean bean = map.get(key);
			System.out.println("value=" + bean.getActionForward());
		}
	}

}
